<template>
  <div class="editModifyPrice" @click.stop="aotuTab = false">
    <div class="header">
      <jc-button
        :btn-arr="['option', 'pass', 'sub', 'save', 'reload', 'list']"
        :disab-arr="['close', 'com1', 'com2', 'cancel', 'toExcel', 'freeze']"
        :list="'/salesPicingList'"
        @refresh="getForm"
        @save="preservation"
        @submit="preservation(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @startUsing="using(1)"
        @forbidden="using(2)"
        @del="delCustom"
        @handleCom1="queryReportForm(1)"
        @handleCom2="queryReportForm(2)"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="modifyPrice" class="layout">
        <jc-form ref="zrf" :option-value="optionValue" :options="options" size="mini" />
        <div style="margin-bottom: 5px;">
          <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button
            size="mini"
            :disabled="isDisabled"
            @click="batchFill"
          >{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <div>
          <jc-table
            serial
            :table-data="modifyPriceTable"
            :table-header="modifyPriceHeader"
            class="jcTable"
            table-height="calc(100vh - 280px)"
            @cellClick="cellClick"
            @rowClick="rowClick"
          >
            <el-table-column
              :label="$t('market.priceList')"
              prop="fname"
              align="center"
              width="130px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.fpriceList"
                  size="mini"
                  :disabled="isDisabled"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handlePriceList(scope.$index)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.custname')"
              prop="fsupplier"
              align="center"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              :label="$t('market.fmaterial')"
              prop="fnumber"
              align="center"
              width="150px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  size="mini"
                  :disabled="isDisabled"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i
                    slot="prefix"
                    class="iconfont icon-jin-rud-ao-bo"
                    @click="sonJumpMateriel(scope.row.fnumber)"
                  />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handleMateriel(scope.row, scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && scope.$index === tableIndex" :class="tableIndex<6 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber1" :materielid="materielid" bom-code="1" @material="materielSelectRow" />
                </div>
              </template>
            </el-table-column>
            <template v-slot:tagSlot="col">
              <el-input-number
                v-model="col.scope.row.fafterPrice"
                size="mini"
                :precision="4"
                :step="0.0001"
                :min="0.0"
                :disabled="isDisabled"
              />
            </template>
            <!-- 生效时间 -->
            <template v-slot:btnState="col">
              <el-date-picker
                v-model="col.scope.row.feffectiveDate"
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                :disabled="isDisabled"
                style="width: 163px"
              />
            </template>
            <!-- 失效时间 -->
            <template v-slot:btnStates="col">
              <el-date-picker
                v-model="col.scope.row.fexpiryDate"
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                :disabled="isDisabled"
                style="width: 163px"
              />
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="other">
        <jc-marker
          ref="log"
          :fnumber="optionValue.billCode"
          other-height="62vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    采购价目列表-->
    <sal-price v-if="openPriceList" @client="priceListSelectRow" />
    <!--    物料编码列表-->
    <materiel v-if="openMaterial" :materielid="materielid" @client="materielSelectRow" />
  </div>
</template>

<script>
import jcForm from '@/components/Form'
import {
  queryTPurPatDetailList,
  updateTPurPat,
  disablePurpat,
  purpatAuSubmit,
  purpatSubmit,
  purpatUnAudit,
  reviewPurPat, undisablePurpat, deletePurpat
} from '@/api/marketManage/salesPicing'
import { Disable, toMxAmina } from '@/components/ToMxamineState'
import jcMarker from '@/components/marker'
import jcButton from '@/components/Button'
import jumpMateriel from '@/components/JumpMateriel'
export default {
  name: 'EditModifyPrice',
  components: {
    numberCode: () => import('@/components/NumberCode'),
    salPrice: () => import('@/views/market/salesPicing/component/salPrice'),
    materiel: () => import('@/views/market/salesPicing/component/materiel'),
    jcForm,
    jcMarker,
    jcButton
  },
  mixins: [jumpMateriel],
  data() {
    return {
      activeName: 'modifyPrice',
      fnumber1: '',
      openPriceList: false, // 采购价目列表弹窗
      openMaterial: false, // 物料编码弹窗
      isDisabled: false,
      aotuTab: false,
      tableHeight: '500px',
      materielid: '',
      teamList: [], // 组织数
      modifyPriceTable: [], // 调价表数据
      modifyPriceHeader: [
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fmodel2'), prop: 'fmodel' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion' },
        { label: this.$t('market.funit'), prop: 'funit', width: 80 },
        { label: this.$t('market.currency2'), prop: 'fcurrency', width: 60 },
        { label: this.$t('market.formerPrice1'), prop: 'fprice', width: 80 },
        { label: this.$t('market.afterPrice1'), type: 'tag', prop: 'fafterPrice', width: '100' },
        { label: this.$t('market.effectiveDate'), prop: 'feffectiveDate', type: 'state', width: '120' },
        { label: this.$t('market.expiryDate'), prop: 'fexpiryDate', type: 'states', width: '120' }
      ],
      otherUrlObject: {}, // 其它审核人
      optionValue: {}, // 表单值
      options: {}, // 表单控件
      tableIndex: 0 // 表格序号
    }
  },
  created() {
    if (this.$route.params.id) {
      this.getForm()
    }
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber1 = fnumber
      }, 1000)
    },
    // 保存调价
    preservation(ev) {
      for (const RES of this.modifyPriceTable) {
        // 缺少fid为undefined, 无法更新
        if (
          !RES.fid ||
          !RES.fmaterialId
        ) {
          this.$message.warning('表格不能为空,或表格值不能为0')
          return
        }
      }
      this.nary = []
      const DETAILS = this.modifyPriceTable.map(item => {
        this.nary.push(item.fnumber)
        const {
          fcustid,
          fpriceListId,
          fmaterialId,
          fafterPrice,
          fcurrencyId,
          fprice,
          fname,
          feffectiveDate,
          fexpiryDate,
          fsrcentryId,
          funitId,
          fsupplierId
        } = item
        return {
          fcustid,
          fprice,
          fcurrencyId,
          fname,
          fpriceListId,
          fmaterialId,
          fafterPrice,
          feffectiveDate,
          fexpiryDate,
          fsrcentryId,
          funitId,
          fsupplierId
        }
      })
      const nary = this.nary.sort()
      for (const index in this.nary) {
        const index1 = Number(index) + 1 * 1
        if (nary[index] === nary[index1]) {
          this.$message.warning('重复的物料：' + nary[index])
          return false
        }
      }
      const { fname, fdescription, fpareason, fid, fdate } = this.optionValue
      const DATA = {
        fid,
        fdate,
        fname,
        fdescription,
        fpaReason: fpareason,
        fdocumentStatus: 'A',
        details: DETAILS
      }
      updateTPurPat(DATA)
        .then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          this.$message({ showClose: true, message: res.message, type: 'success' })
          ev === 1 ? this.submit(1) : this.getForm()
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 获取价目表
    priceListSelectRow(item) {
      if (item.fid) {
        const { fname, fsupplier, fisIncludedTax, fcurrency, fid, fcustid, fcurrencyId } = item
        const modifyPriceTable = this.modifyPriceTable[this.tableIndex]
        modifyPriceTable.fpriceListId = fid
        modifyPriceTable.fpriceList = fname
        modifyPriceTable.fsupplier = fsupplier
        modifyPriceTable.fisIncludedTax = fisIncludedTax
        modifyPriceTable.fcurrency = fcurrency
        modifyPriceTable.fid = fid
        modifyPriceTable.fcustid = fcustid
        modifyPriceTable.fcurrencyId = fcurrencyId
        // 物料编码
        modifyPriceTable.fmaterialId = ''
        modifyPriceTable.fnumber = ''
      }
      this.openPriceList = false
    },
    // 获取物料编码
    materielSelectRow(item) {
      if (item.fmaterialId) {
        const modifyPriceTable = this.modifyPriceTable[this.tableIndex]
        const {
          fmaterialId,
          fnumber,
          fmodel,
          fspecificaTion,
          fdescripTion,
          fprice,
          fsrcentryId,
          funitId,
          funit,
          fname
        } = item
        modifyPriceTable.fmaterialId = fmaterialId
        modifyPriceTable.fnumber = fnumber
        modifyPriceTable.fmodel = fmodel
        modifyPriceTable.fname = fname
        modifyPriceTable.funitId = funitId
        modifyPriceTable.funit = funit
        modifyPriceTable.fspecificaTion = fspecificaTion
        modifyPriceTable.fdescripTion = fdescripTion
        modifyPriceTable.fprice = fprice
        modifyPriceTable.fsrcentryId = fsrcentryId
      }
      this.openMaterial = false
      this.aotuTab = false
    },
    // 获取物料编码
    async handleMateriel(row, index) {
      this.tableIndex = index
      if (!row.fpriceListId) {
        this.$message.warning('价目表未选择或数据出错,请重新选择')
        return
      }
      this.materielid = row.fpriceListId
      this.openMaterial = true
    },
    // 价目表
    async handlePriceList(index) {
      this.tableIndex = index
      this.openPriceList = true
    },
    // 获取表格
    async getForm() {
      const { data: RES } = await queryTPurPatDetailList({
        fid: this.$route.params.id
      })
      this.modifyPriceTable = RES.detail
      this.otherUrlObject = RES
      const { fdataValue, fid, fname, fbillNo, fdescripTion, fdocumentStatus, fpareason, fdate } = toMxAmina(RES)
      const { fforbidStatus } = Disable(RES)
      this.isDisabled = fdocumentStatus === this.$t('market.state1') || fdocumentStatus === this.$t('market.state2')
      this.optionValue = {
        fforbidStatus,
        fdataValue, // 调价原因名称
        fid,
        fpareason, // 调价原因id
        fname, // 名称
        fdocumentStatus, fdate,
        billCode: fbillNo, // 单据编号
        fdescription: fdescripTion // 描述
      }
      this.options = {
        fdocumentStatus: {
          label: this.$t('market.documentstatus'),
          span: 6,
          type: 'tag',
          labelWidth: '100px',
          disabled: 'disabled'
        },
        fdataValue: {
          label: this.$t('market.paReason'),
          disabled: 'disabled',
          span: 6
        },
        fname: {
          label: this.$t('shop.name1'),
          span: 6,
          disabled: this.isDisabled
        },
        billCode: {
          label: this.$t('market.billNo'),
          span: 6,
          disabled: 'disabled'
        },
        fdate: {
          type: 'date',
          label: this.$t('market.placedate'),
          disabled: 'disabled',
          labelWidth: '100px',
          span: 6
        },
        fdescription: {
          label: this.$t('market.descrip'),
          span: 6,
          disabled: this.isDisabled
        },
        fforbidStatus: {
          label: this.$t('market.forbidStatu'),
          span: 6,
          type: 'tag',
          disabled: 'disabled'
        }
      }
    },
    // 其他操作日志
    handleOther(tab) {
      if (tab.name === 'other') {
        this.$refs.log.otherlog()
      }
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.optionValue.billCode] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.getForm()
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审核
    audit(ev) {
      if (ev === 2) {
        this.$confirm('调价表不能反审核！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      const api = ev === 1 ? reviewPurPat : purpatUnAudit
      this.toExamineFun(api)
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? purpatSubmit : purpatAuSubmit
      this.toExamineFun(api)
    },
    // 禁用
    using(ev) {
      const api = ev === 1 ? disablePurpat : undisablePurpat
      this.toExamineFun(api)
    },
    // 删除
    delCustom() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const DATA = { Numbers: [this.optionValue.billCode] }
        deletePurpat(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/salesPicingList' })
        })
      })
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.modifyPriceTable[this.subscript][this.property]
      this.modifyPriceTable.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
          if (this.property === 'fname') {
            res.fid = this.modifyPriceTable[0].fid
            res.fsupplier = this.modifyPriceTable[0].fsupplier
            res.fisIncludedTax = this.modifyPriceTable[0].fisIncludedTax
            res.fcurrency = this.modifyPriceTable[0].fcurrency
          }
        }
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.modifyPriceTable.splice(this.indexSelf, 1)
    },
    // 套打
    queryReportForm(ev) {
      const fbi = this.optionValue.billCode
      if (ev === 1) {
        this.$router.push({ path: `/modifyPriceTao/${fbi}` })
      } else {
        this.$router.push({ path: `/modifyPriceLian/${fbi}` })
      }
    },
    // 新增插入行
    newHang() {
      const data = {
        funit: '',
        fid: '', // 价目ID
        fmaterialId: '', // 物料ID
        fname: '', // 价目表
        fisIncludedTax: false, // 含税
        fnumber: '', // 物料编码
        fafterPrice: '', // 调后单价
        fsupplier: '', // 供应商名称
        fcurrency: '', // 币别
        fdescripTion: '', // 描述
        fspecificaTion: '', // 规格型号
        fprice: '', // 调前单价
        feffectiveDate: new Date(), // 生效时间
        fexpiryDate: '2100-01-01' // 失效时间
      }
      this.modifyPriceTable.push(data)
    }
  }
}
</script>

<style scoped lang="scss">
.editModifyPrice {
  @include listBom;
  padding: 10px;
  background: #FFFFFF;
  display: flex;
  flex-direction: column;

  .layout {
    display: flex;
    flex-direction: column;

    .header {
      margin-bottom: 20px;
    }
    .input-width {
      width: 185px;
    }
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.8vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
}
.el-input__icon {
  cursor: pointer;
}
</style>
